package com.tfr.webflux.handler;

import com.tfr.webflux.exceptions.CheckException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * @description:
 * @author: rain
 * @date: Created in 2021/12/7 21:05
 * @version:
 * @modified By:
 */
@ControllerAdvice
public class CheckAdvice {

  @ExceptionHandler(WebExchangeBindException.class)
  public ResponseEntity<String> webExchangeBindException(WebExchangeBindException e) {
    return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
  }

  @ExceptionHandler(CheckException.class)
  public ResponseEntity<String> checkException(CheckException e) {
    return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
  }

  private String toStr(WebExchangeBindException ex) {
    return ex.getFieldErrors().stream()
        .map(e -> e.getField() + ":" + e.getDefaultMessage())
        .reduce("", (s1, s2) -> s1 + "\n" + s2);
  }
  private String toStr(CheckException ex) {
    return ex.getName()+":错误的值"+ex.getValue();
  }

}
